<template>
  <div class="app-container">
    <el-col :span="20" :offset="2" :xs="24">
      <el-card class="Attend_group_detail">
        <div slot="header" class="clearfix">
          <span>考勤组信息</span>
        </div>
        <el-form
          ref="groupform"
          :model="groupform"
          :rules="rules"
          label-width="100px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="考勤组" prop="attendanceGroupName">
                <span>{{ groupform.attendanceGroupName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考勤规则" prop="attendanceRuleId">
                <span>{{ attendanceRuleIdFormat(groupform) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="考勤地址" prop="attendanceAddId">
                <span>{{ attendanceAddIdFormat(groupform) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="考勤方式" prop="attendanceFromTypeId">
                <span>{{ attendanceFromTypeIdFormat(groupform) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="生效开始" prop="fromDate">
                <span>{{ groupform.fromDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生效结束" prop="thruDate">
                <span>{{ groupform.thruDate }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="状态" prop="statusId">
                <span>{{ statusIdFormat(groupform) }}</span>
              </el-form-item>
            </el-col>
          </el-row> -->
        </el-form>
      </el-card>

      <el-card>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:attend_dept_person:add']"
              >新增</el-button
            >
          </el-col>
        </el-row>
        <el-table
          v-loading="loading"
          :data="attend_dept_personList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />

          <el-table-column
            label="考勤组"
            align="center"
            prop="attendanceGroupId"
          />
          <el-table-column
            v-if="setDeptFlag"
            label="考勤机构"
            align="center"
            :formatter="deptIdFormat"
          />
          <el-table-column
            v-if="setPersonFlag"
            label="考勤员工"
            align="center"
            :formatter="partyIdFormat"
          />
          <el-table-column
            label="最后更新时间"
            align="center"
            prop="lastUpdatedStamp"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{
                parseTime(scope.row.lastUpdatedStamp, "{y}-{m}-{d} {h}:{i}:{s}")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <!-- <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['ehr:attend_group:edit']"
                >修改</el-button
              > -->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:attend_dept_person:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-card>
    </el-col>

    <!-- 添加或修改考勤部门及人员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        v-bind:disabled="detailFlag"
      >
        <el-row>
          <el-col :span="12" v-if="setDeptFlag">
            <el-form-item label="考勤部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择考勤部门">
                <el-option
                  v-for="dict in deptIdOptions"
                  :key="dict.deptId"
                  :label="dict.deptName"
                  :value="dict.deptId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" v-if="setPersonFlag">
            <el-form-item label="员工" prop="partyId">
              <el-select v-model="form.partyId" placeholder="请选择考勤员工">
                <el-option
                  v-for="dict in partyIdOptions"
                  :key="dict.partyId"
                  :label="dict.firstName"
                  :value="dict.partyId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="statusId">
              <el-input v-model="form.statusId" placeholder="请输入状态" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="editFlag" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import LoadPersonSelect from "@/components/LoadPersonSelect";
// person enum api
import { getPersonEnum } from "@/api/ehr/person";
import {
  listAttend_dept_person,
  getAttend_dept_person,
  addAttend_dept_person,
  updateAttend_dept_person,
  delAttend_dept,
  delAttend_person,
} from "@/api/ehr/attend_dept_person";

export default {
  components: { LoadPersonSelect },
  name: "Attend_group_set_dept_person",
  data() {
    return {
      attendanceGroupId: null,
      // 遮罩层
      loading: true,
      // 员工ID业务字典
      partyIdOptions: [],
      // 考勤规则业务字典
      attendanceRuleIdOptions: [],
      // 考勤地址业务字典
      attendanceAddIdOptions: [],
      // 考勤方式业务字典
      attendanceFromTypeIdOptions: [],
      // 状态业务字典
      statusIdOptions: [],
      // 人员字典
      personOptions: [],
      // 考勤部门字典
      deptIdOptions: [],

      // 操作标识,用于区分是新增还是修改
      updateFlag: false,
      // 操作标识,用于区分是详情
      detailFlag: false,
      // 操作标识,用于区分编辑状态
      editFlag: true,
      // 设置考勤部门标识
      setDeptFlag: true,
      // 设置考勤人员标识
      setPersonFlag: false,

      // 总条数
      total: 0,
      // 考勤组设置表格数据
      attend_groupList: [],
      // 考勤部门及人员表格数据
      attend_dept_personList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "", // 排序字段
        isAsc: "", // 升序或降序 大写的 ASC或DESC,为空代表升序
        partyId: null,
        deptId: null,
        statusId: null,
        lastUpdatedStamp: null,
      },
      // 考勤组表单参数
      groupform: {},
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        partyId: [
          { required: true, message: "考勤员工不能为空", trigger: "change" },
        ],
        deptId: [
          { required: true, message: "考勤机构不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.reset();
    if (this.$route.query) {
      this.groupform = JSON.parse(this.$route.query.form);
      this.attendanceGroupId = this.groupform.attendanceGroupId;
      this.form.attendanceGroupId = this.groupform.attendanceGroupId;

      // 通过标识判断是设置考勤机构还是考勤人员
      var setAttendDept = this.groupform.setAttendDept;
      if (setAttendDept) {
        this.rules.partyId[0].required = false;
        this.queryParams.relationType = "group";
        this.setDeptFlag = true;
        this.setPersonFlag = false;
      } else {
        this.rules.deptId[0].required = false;
        this.queryParams.relationType = "person";
        this.setDeptFlag = false;
        this.setPersonFlag = true;
      }
      console.info("groupform:" + JSON.stringify(this.groupform));
    }

    // 考勤规则业务字典
    this.getEntityDicts("attendanceRule:attendanceRuleId:attendanceName").then(
      (response) => {
        this.attendanceRuleIdOptions = response.data;
      }
    );
    // 考勤地址业务字典
    this.getEntityDicts("attendanceAddress:addressId:addressName").then(
      (response) => {
        this.attendanceAddIdOptions = response.data;
      }
    );
    // 考勤方式业务字典
    this.getEnumDicts("ATTEND_SIGN_TYPE").then((response) => {
      this.attendanceFromTypeIdOptions = response.data;
    });
    // 状态业务字典
    this.getEnumDicts("ACTIVE_STOP").then((response) => {
      this.statusIdOptions = response.data;
    });
    // 员工ID业务字典
    this.getEntityDicts("person:partyId:firstName").then((response) => {
      this.partyIdOptions = response.data;
    });
    // 考勤人员字典
    getPersonEnum().then((response) => {
      this.personOptions = response.data;
    });
    // 考勤部门字典
    this.getEntityDicts("sysDept:deptId:deptName").then((response) => {
      this.deptIdOptions = response.data;
    });

    this.getList();
  },
  computed: {
    userInfo() {
      return this.$store.state.user; //当前登录用户信息
    },
  },
  methods: {
    partyIdFormat(row, column) {
      let val = null;
      this.partyIdOptions.forEach((item, index) => {
        if (row.partyId === item.partyId) {
          val = item.firstName;
        }
      });
      return val;
    },
    deptIdFormat(row, column) {
      let val = null;
      this.deptIdOptions.forEach((item, index) => {
        if (row.deptId === item.deptId + "") {
          val = item.deptName;
        }
      });
      return val;
    },
    // 人员字典转换
    personFormat(row, column) {
      let val = null;
      this.personOptions.forEach((item, index) => {
        if (row.partyId === item.partyId) {
          val = item.name;
        }
      });
      return val;
    },

    attendanceRuleIdFormat(row, column) {
      let val = null;
      this.attendanceRuleIdOptions.forEach((item, index) => {
        if (row.attendanceRuleId === item.attendanceRuleId) {
          val = item.attendanceName;
        }
      });
      return val;
    },
    attendanceAddIdFormat(row, column) {
      let val = null;
      this.attendanceAddIdOptions.forEach((item, index) => {
        if (row.attendanceAddId === item.addressId) {
          val = item.addressName;
        }
      });
      return val;
    },
    attendanceFromTypeIdFormat(row, column) {
      let val = null;
      this.attendanceFromTypeIdOptions.forEach((item, index) => {
        if (row.attendanceFromTypeId === item.enumCode) {
          val = item.description;
        }
      });
      return val;
    },
    statusIdFormat(row, column) {
      let val = null;
      this.statusIdOptions.forEach((item, index) => {
        if (row.statusId === item.enumCode) {
          val = item.description;
        }
      });
      return val;
    },
    // /** 查询考勤组设置列表 */
    // getList() {
    //   this.loading = true;
    //   listAttend_group(this.queryParams).then((response) => {
    //     this.attend_groupList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    /** 查询考勤部门及人员列表 */
    getList() {
      this.loading = true;
      this.queryParams.attendanceGroupId = this.attendanceGroupId;
      listAttend_dept_person(this.queryParams).then((response) => {
        this.attend_dept_personList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        attendanceGroupId: null,
        partyId: null,
        deptId: null,
        statusId: null,
        lastUpdatedStamp: null,
        lastUpdatedTxStamp: null,
        createdStamp: null,
        createdTxStamp: null,
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.attendanceGroupId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      (this.editFlag = true), (this.updateFlag = false);
      this.detailFlag = false;
      this.reset();
      this.open = true;
      if (this.setDeptFlag) {
        // 若设置考勤部门，此时考勤人员为 空 " "
        this.form.partyId = " ";
        // 设置考勤组关联部门或是关联员工
        this.form.relationType = "group";
        this.title = "添加考勤部门";
      } else {
        this.form.deptId = " ";
        // 设置考勤组关联部门或是关联员工
        this.form.relationType = "person";
        this.title = "添加考勤人员";
      }
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      (this.editFlag = false), (this.updateFlag = false);
      this.detailFlag = true;
      this.reset();
      const attendanceGroupId = row.attendanceGroupId || this.ids;
      getAttend_dept_person(attendanceGroupId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "考勤部门及人员详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editFlag = true;
      this.updateFlag = true;
      this.detailFlag = false;
      this.reset();
      const attendanceGroupId = row.attendanceGroupId || this.ids;
      getAttend_dept_person(attendanceGroupId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改考勤部门及人员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 设置默认的 考勤组ID
          this.form.attendanceGroupId = this.groupform.attendanceGroupId;

          if (this.form.attendanceGroupId != null && this.updateFlag) {
            updateAttend_dept_person(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAttend_dept_person(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const attendanceGroupIds = row.attendanceGroupId || this.ids;
      this.$modal
        .confirm("是否确认删除数据项？")
        .then(function () {
          if (row.relationType === "group") {
            return delAttend_dept(row.attendanceGroupId, row.deptId);
          } else {
            return delAttend_person(row.attendanceGroupId, row.partyId);
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 编辑 */
    edit() {
      this.editFlag = true;
      this.detailFlag = false;
    },

    close() {
      this.$tab.closePage();
    },
  },
};
</script>
